package com.changgou.search.controller;

import com.changgou.entity.Page;
import com.changgou.search.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Set;

@Controller
@RequestMapping("/search")
public class SearchController {
    @Autowired
    private SearchService searchService;
    @GetMapping("/list")
    public String search(@RequestParam Map<String,String> searchMap, Model model){
        //特殊字符处理
        handlerSearchMap(searchMap);
        //查询结果
        Map<String,Object> resultMap = searchService.search(searchMap);
        model.addAttribute("searchMap",searchMap);
        model.addAttribute("result",resultMap);
        //封装分页数据并返回
        //1.总记录数
        //2.当前页
        //3.每页显示多少条
        Page page = new Page(
                Long.parseLong(resultMap.get("totalPages").toString()),//总页数
                Integer.parseInt(resultMap.get("pageNum").toString()),//当前页
                Integer.parseInt(resultMap.get("pageSize").toString())//每页显示条数
        );
        model.addAttribute("page",page);
        //拼接url
        StringBuilder url = new StringBuilder("/search/list");
        if (searchMap != null && searchMap.size() > 0){
            url.append("?");
            //遍历searchMap拼接url
            for (String key : searchMap.keySet()) {
                if (!"sortField".equals(key) && !"sortRule".equals(key) &&
                        !"pageNum".equals(key) && !"pageSize".equals(key))
                url.append(key).append("=").append(searchMap.get(key)).append("&");
            }
            //http://localhost:9009/search/list?keywords=手机&spec_网络制式=4G&
            String urlString = url.toString();
            //去除路径上的最后一个&
            urlString = urlString.substring(0,urlString.length()-1);
            model.addAttribute("url",urlString);
        }else {
            model.addAttribute("url",url);
        }
        return "search";
    }

    /**
     * 全文检索
     * @param searchMap
     * @return
     */
    @GetMapping
    @ResponseBody
    public Map search(@RequestParam Map<String,String> searchMap){
        handlerSearchMap(searchMap);
        return searchService.search(searchMap);
    }
    //查询参数的特殊字符处理
    private void handlerSearchMap(Map<String, String> searchMap) {
        if (searchMap != null){
            Set<Map.Entry<String, String>> entries = searchMap.entrySet();
            for (Map.Entry<String, String> entry : entries) {
                if (entry.getKey().startsWith("spec_")){
                    searchMap.put(entry.getKey(),entry.getValue().replace("+","%2B"));
                }
            }
        }
    }
}
